﻿using QG.JobBack.BLL.IService;
using QG.JobBack.DAL;
using QH.JobBack.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web.ApplicationServices;

namespace QG.JobBack.BLL.Service
{
    public class RoleService : BaseRepository<RoleInfo>,IRoleService
    {

        /// <summary>
        /// 添加一个角色
        /// </summary>
        /// <param name="RoleInfo"></param>
        /// <returns></returns>
        public ResponseResult<RoleInfo> AddRoleInfo(RoleMoudle roleModule)
        {
            ResponseResult<RoleInfo> result = new ResponseResult<RoleInfo>();

            using (var db=new qgpingEntities())
            {
                
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        //添加角色表
                        RoleInfo role = new RoleInfo();
                        role.CreateTime = DateTime.Now;
                        role.RoleName = roleModule.Name;
                        role.Remark = roleModule.Remark;
                        role.IsEnable = true;

                        db.RoleInfo.Add(role);
                        db.SaveChanges();

                        //角色和组关联表
                        ModuleRole moduleRole = new ModuleRole();

                        moduleRole.ModuleId = roleModule.ModuleId;
                        moduleRole.CreateTime= DateTime.Now; 
                        moduleRole.RoleId = role.RoleId;
                        db.ModuleRole.Add(moduleRole);
                        db.SaveChanges();

                        //提交事务
                        tran.Commit();
                        result.success = true;

                        result.msg =  "添加成功";
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        result.success = false;
                        result.msg = "添加失败";
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 修改一个角色
        /// </summary>
        /// <param name="RoleInfo"></param>
        /// <returns></returns>
        public ResponseResult<RoleMoudle> UpdateRoleInfo(RoleFunctionView roleMoudle)
        {
            ResponseResult<RoleMoudle> result = new ResponseResult<RoleMoudle>();

            using (var db = new qgpingEntities())
            {

                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        //查询角色表并修改
                        RoleInfo role = db.RoleInfo.Find(roleMoudle.RoleId);
                        if (role!=null)
                        {
                            role.RoleName = roleMoudle.RoleName;
                            role.Remark = roleMoudle.Remark;
                            db.Entry(role).State = EntityState.Modified;
                        }

                        //查询角色和组关联表
                        ModuleRole moduleRole = db.ModuleRole.Find(roleMoudle.ModuleId);
                        if(moduleRole!=null)
                        {
                            moduleRole.RoleId = role.RoleId;
                            db.Entry(moduleRole).State = EntityState.Modified;
                        }                     
                        db.SaveChanges();

                        //先删除原来的角色菜单功能关联表对应的记录
                        var oldRoleFunc = db.RoleFunctionPermission.Where(a => a.RoleId == roleMoudle.RoleId).ToList();
                        db.RoleFunctionPermission.RemoveRange(oldRoleFunc);
                        db.SaveChanges();
                        //添加角色菜单功能关联表记录
                        db.RoleFunctionPermission.AddRange(roleMoudle.RoleFunction);
                        db.SaveChanges();

                        //提交事务
                        tran.Commit();
                        result.success = true;

                        result.msg = "修改成功";
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        result.success = false;
                        result.msg = "修改失败";
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 查询角色列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public ResponseResult<RoleUserBase> GetRoleInfoList(int page, int limit, string RoleName)
        {
            ResponseResult<RoleUserBase> result = new ResponseResult<RoleUserBase>();
            //构造查询条件
            using (var db=new qgpingEntities())
            {
                var linq = (from a in db.RoleInfo
                            join b in db.Admin_roleinfo
                            on a.RoleId equals b.RoleId into c
                            from d in c.DefaultIfEmpty()
                            join e in db.Admininfo
                            on d.AdminId equals e.AdminId into f
                            from g in f.DefaultIfEmpty()
                            group new { a, d, g } by
                            new { a.RoleId, a.RoleName, a.Remark } into h
                            select new { h }).AsEnumerable().Select(a => new RoleUserBase()
                            {
                                RoleId = a.h.Key.RoleId,
                                Remark = a.h.Key.Remark,
                                Count = a.h.Count(),

                                RoleName = a.h.Key.RoleName,
                                AdminUserName = String.Join(",", a.h.Select(t =>(t.g==null?"":t.g.AdminName)))
                            });
                var data = linq.ToList();

                //查询条件
                int total;
                
                //如果角色名字不为空，过滤
                if (!string.IsNullOrEmpty(RoleName))
                {
                    data = data.Where(a => a.RoleName.Contains(RoleName)).ToList();
                }
                //对象赋值
                result.code = 0;
                result.count = data.Count;
                result.msg = string.Empty;
                result.data = data.Skip((page-1)*limit).Take(limit).ToList();
                //返回结果
                return result;
            }
                
        }
        /// <summary>
        /// 根据ID删除一个角色
        /// </summary>
        /// <param name="RoleInfo"></param>
        /// <returns></returns>
        public ResponseResult<RoleInfo> DeleteRoleInfoById(int id)
        {
            ResponseResult<RoleInfo> result = new ResponseResult<RoleInfo>();
            result.success = DeleteById(id);
            result.msg = result.success ? "删除成功" : "删除失败";
            return result;
        }

        /// <summary>
        /// 查询单个实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResponseResult<RoleInfo> GetRoleInfo(int id)
        {
            ResponseResult<RoleInfo> result = new ResponseResult<RoleInfo>();
            result.data = Query(a => a.RoleId == id);
            return result;
        }

        ///// <summary>
        ///// 查询所有父级
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public ResponseResult<RoleInfo> GetParentRoleInfo()
        //{
        //    ResponseResult<RoleInfo> result = new ResponseResult<RoleInfo>();
        //    result.data = QueryList(a => a.ParentId == 0);
        //    return result;
        //}


        

        /// <summary>
        /// 根据ID修改状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public ResponseResult<RoleInfo> UpdateStatus(int id, int status)
        {
            ResponseResult<RoleInfo> result = new ResponseResult<RoleInfo>();

            //根据Id获取要修改的对象
            var model = Query(a => a.RoleId == id);
            if (model != null)
            {
                model.IsEnable = status > 0;
                result.success = Update(model);
                return result;
            }

            return result;
        }
    }
}
